import { BadRequestException, Module } from '@nestjs/common'
import { FileService } from './file.service'
import { FileController } from './file.controller'
import { MulterModule } from '@nestjs/platform-express'
import { diskStorage } from 'multer'
import { checkDirAndCreate, getDayjs, isDev, isImage } from '@/shared/utils'
import { OriginList } from '@/shared/constants/indext'
import { extname } from 'path'
import * as nuid from 'nuid'

@Module({
  imports: [
    MulterModule.register({
      storage: diskStorage({
        // destination: `./public/upload/`,
        destination: (req, file, cb) => {
          if (!isDev && !OriginList.includes(req.headers.origin)) {
            console.log('权限不足')
            return
          }

          // 根据上传的文件类型将图片视频音频和其他类型文件分别存到对应英文文件夹
          const mimeType = file.mimetype.split('/')[1]
          let temp = 'other'

          isImage(mimeType) ? (temp = 'image') : ''

          const filePath = `public/uploads/${temp}/${getDayjs()}`

          checkDirAndCreate(filePath) // 判断文件夹是否存在，不存在则自动生成

          return cb(null, `./${filePath}`)
        },
        filename: (req, file, cb) => {
          // 自定义保存后文件名
          const time = getDayjs('HHmmss')
          const filename = `${nuid.next()}_${time}_${Math.round(Math.random() * 1e9)}${extname(file.originalname)}`

          return cb(null, filename)
        },
        fileFilter(req, file, cb) {
          const mimeType = file.mimetype.split('/')[1].toLowerCase()
          let temp = 'other'

          isImage(mimeType) ? (temp = 'image') : ''

          if (temp === 'other') {
            return cb(new BadRequestException('文件格式错误！'), false)
          }

          return cb(null, true)
        },
      }),
    }),
  ],
  controllers: [FileController],
  providers: [FileService],
})
export class FileModule {}
